package leetcode.每日一题;

import org.apache.poi.hssf.record.DVALRecord;
import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/11/27 1:08
 * @description：https://leetcode-cn.com/problems/random-flip-matrix/
 */
public class 随机翻转矩阵 {
    @Test
    public void test() {
        Solution solution = new Solution(3, 1);
        System.out.println(Arrays.toString(solution.flip()));
        System.out.println(Arrays.toString(solution.flip()));
        System.out.println(Arrays.toString(solution.flip()));
        solution.reset();
        System.out.println(Arrays.toString(solution.flip()));

    }

    /*class Solution {

        private Map<Integer, Integer> map = new HashMap<>();
        private int m;
        private int n;
        private int total;
        private Random random = new Random();

        public Solution(int m, int n) {
            this.m = m;
            this.n = n;
            this.total = m * n;
        }

        public int[] flip() {
            int x = random.nextInt(total);
            total--;
            Integer idx = map.getOrDefault(x, x);
            map.put(x, map.getOrDefault(total, total));
            return new int[]{idx / n, idx % n};
        }

        public void reset() {
            total = m * n;
            map.clear();
        }
    }*/

    class Solution {

        private Set<Integer> set = new HashSet<>();
        private int m;
        private int n;
        private int size;
        Random random = new Random();

        public Solution(int m, int n) {
            this.m = m;
            this.n = n;
            this.size = m * n;
        }

        public int[] flip() {
            int ans = random.nextInt(size);
            while (set.contains(ans)) {
                ans = random.nextInt(size);
            }
            set.add(ans);
            return new int[]{ans / n, ans % n};
        }

        public void reset() {
            set.clear();
        }
    }
}
